package com.gxwz.document.core.dao.impl;

import java.io.Serializable;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.orm.hibernate4.HibernateCallback;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.stereotype.Repository;

import com.gxwz.document.business.entity.User;
import com.gxwz.document.core.dao.BaseDao;

@Repository("baseDao")
public class BaseDaoImpl<T> implements BaseDao<T> {

	@Autowired
	@Qualifier("hibernateTemplate")
	private HibernateTemplate hibernateTemplate;
	
	@Override
	public void saveOrUpdate(T entity) {
		hibernateTemplate.saveOrUpdate(entity);
	}

	@Override
	public void update(T entity) {
		hibernateTemplate.update(entity);
	}

	@Override
	public void delete(T entity) {
		hibernateTemplate.delete(entity);
	}

	@Override
	public <T> T findById(Class<T> tClass, Serializable id) {
		return hibernateTemplate.get(tClass, id);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<T> find(String hql, Object... param) {
		return (List<T>) hibernateTemplate.find(hql, param);
	}

	@Override
	public List<T> findByPage(final String hql, final int START_INDEX, final int PAGE_SIZE, final Object... param) {
		return hibernateTemplate.execute(new HibernateCallback<List<T>>() {
			@Override
			public List<T> doInHibernate(Session session) throws HibernateException {
				Query query = session.createQuery(hql);
				if (param != null) {
					for (int i = 0; i < param.length; i++) {
						query.setParameter(i, param[i]);
					}
				}
				query.setFirstResult(START_INDEX);
				query.setMaxResults(PAGE_SIZE);
				return query.list();
			}
		});
	}

}
